package cn.ekuma.epos.android.finder;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import com.android.calculator2.Logic.OnReturnListener;
import com.openbravo.bean.Product;
import com.openbravo.bean.ProductCategory;
import com.openbravo.data.basic.BasicException;
import com.openbravo.data.loader.query.QBFParameter;
import com.openbravo.data.loader.query.QBFParameters;

import cn.ekuma.android.keyBoardinput.KeyBoradInputPanel;
import cn.ekuma.android.ui.scan.history.HistoryItem;
import cn.ekuma.android.ui.scan.history.HistoryManager;
import cn.ekuma.android.ui.tree.TreeElement;
import cn.ekuma.data.dao.I_DataLogic;
import cn.ekuma.data.dao.bean.I_Category;
import  cn.ekuma.data.ui.android.AbstractBaseBeanTreeAdapter;
import  cn.ekuma.data.ui.android.BaseBeanCategorySelecter;
import  cn.ekuma.data.ui.android.BaseBeanListSelecter;
import  cn.ekuma.data.ui.android.OnBaseBeanSelectedListener;
import cn.ekuma.epos.android.adapter.ProductCategoryAdapter;
import cn.ekuma.epos.android.adapter.ProductListAdapter;
import cn.ekuma.epos.datalogic.DataLogicPDA;
import cn.ekuma.epos.db.table.I_Product;
import cn.ekuma.epos.ui.android.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.SlidingDrawer;
import android.widget.Toast;

public class AdvProductSelectActivate  extends Activity implements OnBaseBeanSelectedListener<ProductCategory> {

	private EditText adv_code;
	private BaseBeanListSelecter  adv_productlistSelecter;
	private SlidingDrawer slidingDrawer1;
	private LinearLayout content;
	private ProductListAdapter adapter;
	private HistoryManager historyManager;
	
	public static final String SELECTED_BEANS="selected_beans";
	public static final int MSG_SUCCESS = 0;
    public static final int MSG_FAILURE = 1;
    
	private Button btnSelect,btn_adv_seach;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.adv_product_select);
		historyManager = new HistoryManager(this);
		historyManager.clearHistory();
		adapter=new ProductListAdapter(this);
		adv_code=(EditText) this.findViewById(R.id.adv_code);
		adv_productlistSelecter=(BaseBeanListSelecter) this.findViewById(R.id.adv_productlistSelecter);
		adv_productlistSelecter.setAbstractBaseBeanAdapter(adapter);
		slidingDrawer1=(SlidingDrawer) this.findViewById(R.id.slidingDrawer1);
		content=(LinearLayout) this.findViewById(R.id.content);
		content.addView(createContentPanel());
		slidingDrawer1.setOnDrawerOpenListener(new SlidingDrawer.OnDrawerOpenListener()// 开抽屉
		{
			
			public void onDrawerOpened() {
				adv_productlistSelecter.setVisibility(View.GONE);
																// ，把图片设为向下的
			}
		});
		slidingDrawer1.setOnDrawerCloseListener(new SlidingDrawer.OnDrawerCloseListener() {
			
			public void onDrawerClosed() {
				adv_productlistSelecter.setVisibility(View.VISIBLE);
			}
		});
		loadCategoryTree();
		
		adv_productlistSelecter.setOnBaseBeanSelectedListener(new OnBaseBeanSelectedListener<Product>(){
			public void baseBeanSelected(final Product obj, int position) {
		    	AlertDialog.Builder builder = new AlertDialog.Builder(AdvProductSelectActivate.this);
		    	KeyBoradInputPanel inputView=new KeyBoradInputPanel(AdvProductSelectActivate.this);
		        builder.setView(inputView);
		        final AlertDialog dialog=builder.create();
		        inputView.setInputListener(new OnReturnListener(){
					public void onReturn(String value) {
						   double retValue=0;
						   if(value!=null&&value.length()>0){
				              retValue=Double.valueOf(value);
						   HistoryItem selectItem=new HistoryItem(null, obj.getCode(), obj.getName(), new Double(retValue));
						   historyManager.addHistoryItem(selectItem);
						}
						dialog.dismiss();	
					}

					public void onCommand(int command,String value) {
						onReturn(value);
						
					}
		        }); 
		        dialog.show();  
			}
		});
		
		btnSelect=(Button) this.findViewById(R.id.btn_advproductSelect);
		btnSelect.setOnClickListener(new OnClickListener(){
			public void onClick(View v) {
				 HashMap<String,Double> returnBean=historyManager.buildLocalHistory();
		    	  if(!returnBean.isEmpty()){
		    	     Intent result = new Intent();
		  		     result.putExtra(SELECTED_BEANS, returnBean);
		    	     setResult(RESULT_OK, result);
		    	  }
		    	  finish();
			}
		});
		
		btn_adv_seach=(Button) this.findViewById(R.id.btn_adv_seach);
		btn_adv_seach.setOnClickListener(new OnClickListener(){
			public void onClick(View v) {
				String code=adv_code.getText().toString();
				if(code.length()>0){
					final QBFParameters paras=new QBFParameters();
					paras.or(new QBFParameter(I_Product.NAME).link(code));
				    slidingDrawer1.close();
					final ProgressDialog dialog = ProgressDialog.show(AdvProductSelectActivate.this, "", 
					        "查旬中，请稍等 …", true, true);
					new Thread(){
						@Override
						public void run(){
							I_DataLogic dlERP=DataLogicPDA.getDataLogic();
							try {
								List<Product> lists=dlERP.queryByQBFParameters(Product.class.getName(), paras);
								if(lists==null)
									lists=new ArrayList();
								mListHandler.obtainMessage(MSG_SUCCESS, lists).sendToTarget();			
							} catch (BasicException e) {
								e.printStackTrace();
								mListHandler.obtainMessage(MSG_FAILURE).sendToTarget();//获取图片失败   
							}
							dialog.dismiss(); 
						}
						}.start();		
				}
			}
		});
	}
	
	protected void loadCategoryTree() {
		final ProgressDialog dialog = ProgressDialog.show(this, "", 
		        "查旬中，请稍等 …", true, true);
		new Thread(){
			@Override
			public void run(){
				I_DataLogic dlERP=DataLogicPDA.getDataLogic();
				try {
					List<ProductCategory> lists=dlERP.listWithClassName(ProductCategory.class.getName());
					if(lists==null)
						lists=new ArrayList();
				    mHandler.obtainMessage(MSG_SUCCESS, lists).sendToTarget();			
				} catch (BasicException e) {
					e.printStackTrace();
					mHandler.obtainMessage(MSG_FAILURE).sendToTarget();//获取图片失败   
				}
				dialog.dismiss(); 
			}
			}.start();		
	}

	
	protected Handler mListHandler = new Handler() {  
        public void handleMessage (Message msg) {//此方法在ui线程运行   
            switch(msg.what) {  
            case MSG_SUCCESS:  
            	adapter.clear();
				for(Product info:(List<Product>)msg.obj)
					adapter.add(info);
                break;  
            case MSG_FAILURE:  
                Toast.makeText(getApplication(), "执行出错了", Toast.LENGTH_LONG).show();  
                break;
            }  
        }  
    };
	
	
	AbstractBaseBeanTreeAdapter listAdapter;

	

	public View createContentPanel() {
        BaseBeanCategorySelecter main=new BaseBeanCategorySelecter<ProductCategory>(this);
		listAdapter=getTreeAdapter();
		main.setAbstractBaseBeanTreeAdapter(listAdapter);
		main.setOnBaseBeanSelectedListener(this);
		return main;
	}

	public  AbstractBaseBeanTreeAdapter getTreeAdapter(){
		return new ProductCategoryAdapter(this);
	}
	
	
	protected Handler mHandler = new Handler() {  
        public void handleMessage (Message msg) {//此方法在ui线程运行   
            switch(msg.what) {  
            case MSG_SUCCESS:  
            	listAdapter.setRootNode(buildTree((List<I_Category>) msg.obj));
                break;
            case MSG_FAILURE:  
            	
                Toast.makeText(getApplication(), "执行出错了", Toast.LENGTH_LONG).show();  
                break;
            }  
        }  
    };
    
    
    private List<TreeElement> buildTree(List<I_Category> beans){
    	TreeElement root=new TreeElement("根",null);
    	buildTreeForList((List<I_Category>) beans,root);
		return root.getChildren();
    }
    
    private void buildTreeForList(List<I_Category> m_aData,TreeElement parent){
		if(m_aData.isEmpty())
			return;
		List<I_Category> recapt=new ArrayList();
		TreeElement temp;
		for(I_Category c:m_aData){
			if(isChinad(parent,c)){
				temp=new TreeElement(c.getName(), (Object)c);
				parent.addChild(temp);
			}else 
				recapt.add(c);
		}
		for(int i=0;i<parent.childCount();i++)
			buildTreeForList(recapt,(TreeElement) parent.getChild(i));
	}
    
    
    private boolean isChinad(TreeElement parent,I_Category category1){
    	I_Category category=(I_Category) parent.getTag();
    	boolean isChinad=false;
		if(category==null){
			if(category1.getM_sParentID()==null)
				isChinad=true;
		}else if(category.getID().equalsIgnoreCase(category1.getM_sParentID()))
			isChinad=true;
		return  isChinad;
    }

	public void baseBeanSelected(final ProductCategory obj, int position) {
		slidingDrawer1.close();
		final ProgressDialog dialog = ProgressDialog.show(this, "", 
		        "查旬中，请稍等 …", true, true);
		new Thread(){
			@Override
			public void run(){
				I_DataLogic dlERP=DataLogicPDA.getDataLogic();
				try {
					List<Product> lists=dlERP.listWithParentClassAndKey(Product.class.getName(), ProductCategory.class.getName(), obj.getID());
					if(lists==null)
						lists=new ArrayList();
					mListHandler.obtainMessage(MSG_SUCCESS, lists).sendToTarget();			
				} catch (BasicException e) {
					e.printStackTrace();
					mListHandler.obtainMessage(MSG_FAILURE).sendToTarget();//获取图片失败   
				}
				dialog.dismiss(); 
			}
			}.start();		
	}
}
